import Effect2D from "./Effect2D";
import eUtils from '../../utils/every-utils'
import DrawnStep from "../DrawnStep/DrawnStep";

export default class TrackEffect extends Effect2D {
    /**
     * @param step {DrawnStep}
     * @param timer {number=200}
     * @param alpha
     * @param less
     */
    constructor(step, timer = 1, alpha = 1, less = 0.01) {
        super();
        this.step = step;
        this.timer = timer;
        this.items = [];
        this.count = 0;
        this.alpha = alpha;
        this.less = less;
    }

    beDrawn(painter) {
        let _this = this;

        if (++this.count >= this.timer) {
            this.items.push([
                eUtils.cloneObject(this.step),
                new class AlphaController {
                    constructor(alpha = _this.alpha) {
                        this.alpha = alpha;
                    }

                    alphaLess() {
                        this.alpha -= _this.less;
                        if (this.alpha <= 0) {
                            this.alpha = 0;
                        }
                        return this.alpha;
                    }
                }()
            ]);
            this.count %= this.timer;
        }
        this.items = this.items.filter(item => {
            painter.drawInSession((p) => {
                p.globalAlpha = item[1].alphaLess();
                const step = item[0];
                step.__proto__ = DrawnStep.prototype;
                p.drawingFollowStep(step);
            });
            return item[1].alphaLess() > 0;
        });
    }
}